import crypto from "crypto-js" 
import Buffer from "vue-buffer";
// var crypto = require('crypto')
function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}
WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode
  var sessionKey = Buffer(this.sessionKey, 'base64')
  encryptedData = Buffer(encryptedData, 'base64')
  iv = Buffer(iv, 'base64')
  try {
     // 解密
	  console.log(sessionKey, iv)
    var decipher = crypto.AES.decrypt(iv,sessionKey,{
			mode: crypto.mode.ECB,
			padding: crypto.pad.Pkcs7,
		})
		// .toString(crypto.enc.Utf8)

		console.log(decipher)
    // 设置自动 padding 为 true，删除填充补位
    decipher.setAutoPadding(true)
    var decoded = decipher.update(encryptedData, 'binary', 'utf8')
    decoded += decipher.final('utf8')
    
    decoded = JSON.parse(decoded)

  } catch (err) {
    throw new Error('Illegal Buffer')
  }

  if (decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer')
  }

  return decoded
}

export default WXBizDataCrypt
